package day11.gec.dao.Impl;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import day11.gec.bean.User;
import day11.gec.dao.UserDao;
import day11.gec.utils.JDBCUtil3;

public class UserDaoImpl4 implements UserDao {

	@Override
	public void save(User user) {
		String sql = "insert into t_user(name,password)values(?,?)";
		
		Object[] strs = {user.getName(),user.getPassword()};
		try {
			//只管sql，参数传进来 
			JDBCUtil3.executeUpdate(sql, strs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil3.closeConn(JDBCUtil3.getCo(), JDBCUtil3.getS(), null);
		}

	}

	@Override
	public void update(User user) {
		String sql = "update t_user set name = ?,password=? where id = ?";
		Object[] strs = {user.getName(),user.getPassword(),user.getId()};
		try {
			JDBCUtil3.executeUpdate(sql, strs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil3.closeConn(JDBCUtil3.getCo(), JDBCUtil3.getS(), null);
		}
	}

	@Override
	public void delete(User user) {
		String sql = "delete from t_user where id = ?";
		try {
			Object[] strs = {user.getId()};
			JDBCUtil3.executeUpdate(sql, strs);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil3.closeConn(JDBCUtil3.getCo(), JDBCUtil3.getS(), null);
		}
	}

	@Override
	public User getUserById(int id) {
		String sql = "select * from t_user where id = ?";
		ResultSet rs = null;
		try {
			Object[] strs = {id};
			rs = JDBCUtil3.executeQuery(sql, strs);
			// 返回结果集 遍历
			while (rs.next()) {
				// 创建用户对象
				User user = new User();
				int uid = rs.getInt(1);
				String name = rs.getString("name");
				String password = rs.getString("password");

				user.setId(uid);
				user.setName(name);
				user.setPassword(password);

				// 返回用户信息
				return user;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil3.closeConn(JDBCUtil3.getCo(), JDBCUtil3.getS(), rs);
		}
		return null;
	}

	@Override
	public List<User> findUsers() {
		// 定义集合
		List<User> users = new ArrayList<>();
		ResultSet rs = null;
		try {
			String sql = "select * from t_user";
			rs = JDBCUtil3.executeQuery(sql, null);
			// 返回结果集 遍历
			while (rs.next()) {
				// 创建用户对象
				User user = new User();
				int uid = rs.getInt(1);
				String name = rs.getString("name");
				String password = rs.getString("password");

				user.setId(uid);
				user.setName(name);
				user.setPassword(password);
				// 每个用户放到集合里面
				users.add(user);
			}

			return users;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtil3.closeConn(JDBCUtil3.getCo(), JDBCUtil3.getS(), rs);
		}
		return null;
	}

}
